package spring.mvc.response;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

/**
 * 重复读取 HttpServletRequest 的包装类
 *
 * @author ME
 */
public class RequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        String method = request.getMethod();
        Enumeration<String> names = request.getHeaderNames();
        String bodyStr = HttpHelper.getBodyString(request);
        body = bodyStr.getBytes(StandardCharsets.UTF_8);

        System.out.println("请求头：");
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            System.out.println(name + "：\t\t" + request.getHeader(name));
        }
        System.out.println("请求体：" + bodyStr);
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    /**
     * 在使用 @RequestBody 注解的时候，其实框架是调用了 getInputStream() 方法，所以我们要重写这个方法
     */
    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);

        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public String getHeader(String name) {
        return super.getHeader(name);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        return super.getHeaderNames();
    }

}
